<template>
    <div class="pt-20">
        <el-form :model="userForm" label-width="auto" class="max-w-md m-4 mx-auto" size="large">
            <el-form-item label="Username">
                <el-input v-model="userForm.username" />
            </el-form-item>
            <el-form-item label="Password">
                <el-input v-model="userForm.password" type="password" />
            </el-form-item>
            <el-form-item label="Captcha">
                <el-input v-model="userForm.captcha" class="flex-1">
                    <template #append>
                        <div v-html="captcha.captchaSvg" @click="fetchCaptcha"></div>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label=" ">
                <el-button @click="signIn" type="primary">Sign in</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
definePageMeta({
  layout: 'empty'
})

const captcha = reactive({
    captchaId: '',
    captchaSvg: ''
})

const userForm = reactive({
    username: '',
    password: '',
    captchaId: '',
    captcha: ''
})

async function fetchCaptcha() {
    const url = `https://xingapi.com/api/v1/users/login/captcha`
    const { data } = await $fetch(url)
    captcha.captchaId = data.captchaId
    captcha.captchaSvg = data.captchaSvg
    userForm.captchaId = data.captchaId
}

async function signIn() {
    const url = `https://xingapi.com/api/v1/users/login`
    try {
        const { data } = await $fetch(url, {
            method: 'POST',
            body: userForm
        })
        const token = useCookie('token', { maxAge: data.expiresIn })
        token.value = data.token
        navigateTo('/')
    } catch (err) {
        console.log(err.message)
        fetchCaptcha()
    }
}

onBeforeMount(() => {
    fetchCaptcha()
})
</script>